<template>
  <a-tree-select
    v-model="searchValue"
    class="sc-tree-select"
    dropdownClassName="sc-tree-select-body"
    blockNode
    show-icon
    allow-clear
    show-search
    treeDefaultExpandAll
    treeNodeFilterProp="label"
    :dropdownMatchSelectWidth="true"
    :dropdown-style="{ height: '240px', overflow: 'auto' }"
    :treeData="treeData"
    @change="onchange">
    <template slot-scope="text" slot="doc">
      <i class="sc-tree-select-icon xicon-file" v-show="type === 'template'" />
      <i class="sc-tree-select-icon xicon-xuanren" v-show="type === 'sender'" />
      {{ text.label }}
    </template>
  </a-tree-select>
</template>
<script>
  import {getParams} from "@/utils";

  const SELECT_TEMPLATE = 'template';

  export default {
    props: {
      attr: {
        type: Object,
        default: () => {}
      },
      data: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String
      },
      allCount: {
        type: Number
      }
    },
    data() {
      return {
        searchValue: '',
        treeData: [],
        targetKeys: [],
        mapData: {}
      };
    },
    watch: {
      data(newVal) {
        if (this.type === SELECT_TEMPLATE) {
          if (!newVal || !newVal.templatePanel) {
            this.searchValue = '';
            return;
          }
          if (newVal.templatePanel.indexOf('_') !== -1) {
            this.searchValue = newVal.templatePanel.split('_')[1];
            return;
          }
          this.searchValue = newVal.templatePanel;
        } else {
          this.searchValue = newVal?.realSenderPanel ? newVal.realSenderPanel.split('|')[1] : '';
        }
      }
    },
    async created() {
      if (this.type === SELECT_TEMPLATE) {
        let templatePanel = this.data?.templatePanel;
        if (templatePanel) {
          let value = templatePanel;
          if (templatePanel.startsWith('C_')) {
            value = templatePanel.split('_')[1];
          }
          this.targetKeys.push(value);
        }
      } else {
        let value = this.data?.realSenderPanel?.split('|')[1];
        if (value) {
          this.targetKeys.push(value);
        }
      }
      this.urlParamObj = getParams(window.location.search);
      this.treeData = await this.getTreeData();
    },

    methods: {
      valueChange(targetKeys) {
        let targetObj = this.mapData[targetKeys[0]];
        let retValue = {};
        if (this.type === SELECT_TEMPLATE) {
          if (!targetObj) {
            return retValue;
          }
          retValue.text = targetObj.name;
          if (targetObj.type === 'template') {
            retValue.templatePanel = targetObj.id;
            return retValue;
          }
          if (targetObj.unionIds && targetObj.unionIds.indexOf(',') > -1) {
            retValue.templatePanel = targetObj.unionIds
              .split(',')
              .map((id) => 'C_' + id)
              .join(',');
            return retValue;
          }
          retValue.templatePanel = 'C_' + targetObj.id;
          return retValue;
        }
        if (!targetObj) {
          return retValue;
        }
        retValue.text = targetObj.name;
        retValue.realSenderPanel = targetObj.type + '|' + targetObj.id;
        if (!(targetObj.type === 'Account' || targetObj.type === 'Department')) {
          retValue.senderPanel = targetObj.type + '|' + targetObj.id;
          return retValue;
        }
        let memberDetail = this.findAllMember4ChildrenTree(targetObj);
        if (memberDetail.count > 50) {
          //大于规定值则不考虑兼职/副岗
          retValue.senderPanel = targetObj.type + '|' + targetObj.id;
          return retValue;
        }
        retValue.senderPanel = memberDetail.detail;
        return retValue;
      },
      findAllMember4ChildrenTree(node) {
        //设置默认值
        let memberDetail = {};
        let detailArr = [];

        let allChildrenNodes = [];
        this.getAllChildrenNodes(node, allChildrenNodes);

        for (let i = 0; i < allChildrenNodes.length; i++) {
          if ('Member' == allChildrenNodes[i].type) {
            detailArr.push(allChildrenNodes[i].type + '|' + allChildrenNodes[i].id);
          }
        }
        memberDetail.detail = detailArr.join(',');
        memberDetail.count = detailArr.length;

        return memberDetail;
      },
      getAllChildrenNodes(treeNode, result) {
        if (treeNode.children.length) {
          let childrenNodes = treeNode.children;
          if (childrenNodes) {
            for (let i = 0; i < childrenNodes.length; i++) {
              result.push(childrenNodes[i]);
              result = this.getAllChildrenNodes(childrenNodes[i], result);
            }
          }
        }
        return result;
      },
      async getTreeData() {
        const {
            propertyId = '',
            propertyFrom = '',
            fragmentId = '',
            ordinal = '',
            section = '',
            bigTitleIndex = ''
        } = this.urlParamObj||{};
        const memberId = window._currentUser.id;
        const method =
          this.type === SELECT_TEMPLATE
            ? 'getTreeData4PendingTemplate'
            : 'getTreeData4PendingStaff';
        const params = { memberId };
        console.log('this.allCount', this.allCount);
        if (this.allCount != undefined) {
          params.allCount = parseInt(this.allCount, 10);
        }
        console.log('params', params);
        const args = `managerMethod=${method}&arguments=${JSON.stringify(params)}`;
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=pendingManager&propertyId=${propertyId}&propertyFrom=${propertyFrom}
        &fragmentId=${fragmentId}&ordinal=${ordinal}&section=${section}&bigTitleIndex=${bigTitleIndex}&rnd=${Math.random()}`;
        const data = await window.axios.post(url, args).then((ret) => ret?.data);
        console.log(this.arrayToTree(data), 'this.arrayToTree(data)');
        return this.arrayToTree(data);
      },
      arrayToTree(items = []) {
        // 存放结果集
        let res = [];
        // 判断对象是否有某个属性
        let map = {};

        // 边做map存储，边找对应关系
        for (const i of items) {
          map[i.id] = {
            ...i,
            label: i.name,
            key: i.id,
            value: i.id,
            children: map[i.id] ? map[i.id].children : []
          };
          let newItem = map[i.id];
          this.mapData[i.id] = newItem;
          if (i.pId === null || i.id === i.pId) {
            res.push(newItem);
          } else {
            if (!map[i.pId]) {
              map[i.pId] = {
                children: []
              };
            }
            map[i.pId].children.push(newItem);
            map[i.pId].scopedSlots = { title: 'folder' };
            if (!newItem.children.length) {
              newItem.scopedSlots = { title: 'doc' };
            }
          }
        }
        return res;
      },
      onchange(value) {
        const targetKeys = [value];
        this.targetKeys = targetKeys;
        const params = this.valueChange(targetKeys);
        this.$emit('triggerValueChange', params);
      }
    }
  };
</script>
<style lang="scss">
  .sc-tree-select {
    width: 100%;
    height: 100%;
    // fiber 重写了高度，这边需要适配一下
    .ant-select-selection--single {
      height: 30px;
    }
    .ant-select-selection-selected-value {
      line-height: 28px;
      i {
        display: none;
      }
    }
  }
  .sc-tree-select-icon {
    font-size: 14px;
    color: #595959;
  }
  .sc-tree-select-body {
    .ant-select-tree {
      padding-top: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
    }
    .ant-select-tree li .ant-select-tree-node-content-wrapper {
      min-width: calc(100% - 20px);
      width: auto;
      padding: 3px 1px;
    }
    .ant-select-tree li .ant-select-tree-node-content-wrapper-normal {
      min-width: 100%;
    }
    .ant-select-tree li span.ant-select-tree-switcher.ant-select-tree-switcher-noop {
      display: none;
    }
    .ant-select-tree li {
      margin: 0;
    }
    .ant-select-tree li ul {
      margin-bottom: 1px;
    }
  }
</style>
